package com.hare.auth.utils;


import com.hare.common.global.Audience;
import com.hare.common.global.constant.BaseConstant;
import com.hare.common_redis.RedisCache;

import io.jsonwebtoken.Header;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;

import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: Hare
 * @description: JWT相关工具
 * @author: Hare
 * @create: 2021-08-18 15:23
 * @Version 6.0.1
 **/
@Component
public class JwtUtils {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private Audience audience;


    /**
     * 生成jwt
     * 使用Hs256算法, 私匙使用固定JWT_SEC秘钥
     *
     * @param seurity jwt秘钥
     * @param claims  用户名 可根据需要传递的信息添加更多
     * @return
     */
    public static String createJWT(String seurity, Map<String, Object> claims) {
        SecretKey secretKey = Jwts.SIG.HS256.key().build();

        Header Headers = Jwts.header()
                .keyId("aKeyId")//秘钥ID, 一般不写
                .add("Key","Value")
                // ... 可add多个参数 ...
                .build(); //构建对象


        JwtBuilder builder = Jwts.builder()
                // header
                .setHeaderParam("typ", "JWT")
                // payload
                .claim(BaseConstant.USER_NAME, claims.get("userName").toString())
                .claim(BaseConstant.USER_ID, claims.get("userId").toString())
                .setSubject(claims.get("userName").toString())
                .setIssuer(claims.get("issuer").toString())
                .setAudience(claims.get("audience").toString())
                // signature
                .signWith(secretKey, Jwts.SIG.HS256);
        return builder.compact();
    }





    /**
     * 获取token
     *
     * @param token
     * @return
     */
    public static String getTokenKey(String token) {
        return BaseConstant.PREFIX_TOKEN + token;
    }


    /**
     * 刷新token
     *
     * @param key
     */
    public void refreshJwtTime(String key) {
        //查找剩余的过期时间
        long surplusOverdue = redisCache.getExpire(key);
        //获取刷新时间
        long refreshTime = audience.getRefreshSecond();
        if (surplusOverdue <= refreshTime) {
            redisCache.expire(key, audience.getTtlSecond(), TimeUnit.SECONDS);
        }
    }
}
